"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = __importDefault(require("url"));
const koa_router_1 = __importDefault(require("koa-router"));
const DBConnectTool_1 = __importDefault(require("../com/DBTool/DBConnectTool"));
const ContentTypeTool_1 = __importDefault(require("../lib/ContentTypeTool"));
const DBRoutes = new koa_router_1.default({ prefix: '/DBService' });
DBRoutes
    .get('/(.*)', async (ctx) => {
    let reqUrl = ctx.request.url.replace('/DBService/', '');
    let urlObj = url_1.default.parse(reqUrl, true);
    reqUrl = decodeURI(urlObj.pathname);
    let pathItem = reqUrl.split('/');
    if (pathItem?.length) {
        let DBName = pathItem.shift();
        let fullPath = '/' + pathItem.join('/');
        let file;
        let dbTool = await DBConnectTool_1.default.openDB(DBName);
        if (dbTool) {
            if (DBName.endsWith('-Index')) {
                const indexDB = await DBConnectTool_1.default.openDB(DBName);
                const indexInfo = await indexDB.getFileByFullPath(fullPath, false);
                const md5 = indexInfo?.file_md5;
                if (md5) {
                    const dataDBName = DBName.endsWith('-16x16-Index') ? DBName.replace('-16x16-Index', '-') : DBName.replace('-Index', '-');
                    const dbTool = await DBConnectTool_1.default.openDB(dataDBName + md5.substring(0, DBName.endsWith('-16x16-Index') ? 2 : 1));
                    file = await dbTool.getFileByFullPath(fullPath, false);
                }
            }
            else {
                file = await dbTool.getFileByFullPath(fullPath, false);
            }
            if (!file || !file.file_data) {
                ctx.status = 422;
                ctx.set('Content-Type', 'application/json;charset=utf-8');
                ctx.body = JSON.stringify({ message: `资源库【${DBName}】连接成功，但找不到该文件资源，路径：【${fullPath}】` });
            }
            else {
                let contentType = ContentTypeTool_1.default.getContentType(file.file_name);
                file.file_zip === 'gzip' && (ctx.set('Content-Encoding', 'gzip'));
                ctx.set('Content-Type', contentType);
                ctx.body = file.file_data;
            }
        }
        else {
            ctx.status = 422;
            ctx.set('Content-Type', 'application/json;charset=utf-8');
            ctx.body = JSON.stringify({ message: `资源库不存在【${DBName}】，请检查 Url` });
            return;
        }
    }
});
exports.default = DBRoutes;
